// @Title  protobuff_transport.go
// @Description  发送protobuff报文到指定服务器
// @Author  IT搬运工
// @Update
package transport

import (
	"fmt"
	"intelligentgateway/src/container"
	"intelligentgateway/src/logs"
	"intelligentgateway/src/server"
	"net"
	"strconv"
	"time"
)

//连接云平台
func connectTransportTcp() (net.Conn, string) {
	config := server.GetProtobuffTransportTcpConfig()

	conn, err := net.Dial("tcp", config.Ip+":"+strconv.Itoa(config.Port))
	if err != nil {
		timer := time.NewTicker(10 * time.Minute)
		defer timer.Stop()
		for range timer.C {
			conn, err = net.Dial("tcp", config.Ip+":"+strconv.Itoa(config.Port))
			if err == nil {
				//连接正常
				timer.Stop()
				return conn, config.ChannelId
			}

		}
	}
	return conn, config.ChannelId

}

func StartTransportMsg() {
	conn, channelId := connectTransportTcp()
	//创建通道
	container.CreateDevChannel(channelId)

	//设置通道状态
	channelStatus := &container.ChannelStatus{
		IsRun: true,
	}
	container.NoExpirationSet(channelId, channelStatus)

	//监听是否有数据发送
	go receiveMsg(conn)

	channel := container.GetDevChannel(channelId)

	for {
		data := <-channel
		fmt.Printf("receive len=%d", len(data))
		_, err := conn.Write(data)
		if err != nil {
			closeResource(channelId)
			conn.Close()
		}
	}
}

//当连接断开时关闭资源
func closeResource(channelId string) {

	status := container.ChannelStatus{
		IsRun: false,
	}
	container.NoExpirationSet(channelId, status)
	channel := container.GetDevChannel(channelId)
	if nil != channel {
		//关闭通道
		close(channel)
	}
	container.DestroyDevChannel(channelId)

}

//接受数据
func receiveMsg(conn net.Conn) {
	buf := [512]byte{}
	for {
		n, err := conn.Read(buf[:])
		if err != nil {
			break
		}
		if n > 0 {
			fmt.Printf("receive len=%d", n)
			logs.Debug("len=%d", n)
		}
	}

}
